<?php
/**
 * Create by 11li
 * Date 2020/2/9
 * Time 21:44
 *
 */

namespace app\common\service;


use app\common\model\Order;
use think\Db;
use think\Exception;

class OrderCommentService extends BaseService
{
	
	/**
	 * 添加订单评价
	 * @param $orderId
	 * @param $goodsComment
	 * @param $userId
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function addComment($orderId, $goodsComment, $userId) {
		if(empty($orderId) || empty($goodsComment)) {
			$this->error = '参数错误';
			return false;
		}
		
		$orderModel = new Order();
		$order = $orderModel->getOrderById($orderId);
		if(!$order || $order['user_id'] != $userId || $order['comment_status'] != 0) {
			$this->error = '订单已评价';
			return false;
		}
		
		$model = new \app\common\model\OrderComment();
		$model->startTrans();
		try {
			
			//更改订单评价状态
			$orderRes = $orderModel->changeOrderData($orderId, ['comment_status' => StatusService::STATUS_NORMAL]);
			if(!$orderRes) {
				throw new Exception('更改评价状态出错');
			}
			
			//添加评价信息
			foreach ($goodsComment as &$item) {
				$item['order_id'] = $orderId;
				$item['user_id'] = $userId;
			}
			
			$commentRes = $model->isUpdate(false)->saveAll($goodsComment);
			if(!$commentRes) {
				throw new Exception('添加订单评价出错');
			}
			
			$model->commit();
			return true;
		} catch (Exception $e) {
			$model->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	public function getList($page)
	{
		$where = [
			'c.status' => StatusService::STATUS_NORMAL
		];
		
		$obj = Db::name('orderComment')->alias('c');
		
		$total = $obj->where($where)->count();
		$list = [];
		if($total > 0) {
			$list = Db::name('orderComment')->alias('c')
				->join('goods g', 'c.goods_id = g.id', 'left')
				->join('user u', 'u.id = c.user_id', 'left')
				->where($where)
				->field('c.id, c.goods_id, g.goods_name, c.images, c.score, u.avatar, u.nickname, c.content, c.images')
				->page($page)
				->order(['c.update_time' => 'desc'])
				->select();
			
			if($list) {
				foreach ($list as &$item) {
					$item['images'] = array_filter(explode(',', $item['images']));
				}
			}
		}
		
		return [
			'total' => $total,
			'list' => $list,
			'page' => $page
		];
	}
}